package org.example.springboot.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.example.springboot.common.Result;
import org.example.springboot.entity.*;
import org.example.springboot.mapper.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ProductService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ProductService.class);

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ReviewMapper reviewMapper;

    @Autowired
    private FavoriteMapper favoriteMapper;

    @Autowired
    private FileService fileService;

    @Autowired
    private CarouselItemMapper carouselItemMapper;

    @Resource
    private StockInMapper stockInMapper;
    @Resource
    private StockOutMapper stockOutMapper;

    @Resource
    private LogisticsMapper logisticsMapper;

    public Result<?> createProduct(Product product) {
        try {
            int result = productMapper.insert(product);
            if (result > 0) {
                LOGGER.info("创建商品成功，商品ID：{}", product.getId());
                return Result.success(product);
            }
            return Result.error("-1", "创建商品失败");
        } catch (Exception e) {
            LOGGER.error("创建商品失败：{}", e.getMessage());
            return Result.error("-1", "创建商品失败：" + e.getMessage());
        }
    }

    public Result<?> updateProduct(Long id, Product product) {
        Product oldProduct = productMapper.selectById(id);
        if(oldProduct == null) {
            return Result.error("-1", "商品不存在");
        }
        
        // 检查图片是否变更，如果变更了，后端不需要删除旧图片
        // 因为前端在上传新图片前已经调用了删除接口
        String oldImg = oldProduct.getImageUrl();
            String newImg = product.getImageUrl();
        
        product.setId(id);
        try {
            // 检查库存是否合法
            if (product.getStock() < 0) {
                return Result.error("-1", "库存不能为负数");
            }

            int result = productMapper.updateById(product);
            if (result > 0) {
                LOGGER.info("更新商品成功，商品ID：{}", id);
                return Result.success(product);
            }
            return Result.error("-1", "更新商品失败");
        } catch (Exception e) {
            LOGGER.error("更新商品失败：{}", e.getMessage());
            return Result.error("-1", "更新商品失败：" + e.getMessage());
        }
    }

    public Result<?> deleteProduct(Long id) {
        try {
            Product product = productMapper.selectById(id);
            if (product == null) {
                return Result.error("-1", "商品不存在");
            }

            int deleteRelateResult = deleteRelate(product);
            if (deleteRelateResult < 0) {
                return Result.error("-1", "删除关联记录失败");
            }
            int res = productMapper.deleteById(id);
            if (res <= 0) {
                return Result.error("-1", "删除商品失败");
            }
           return Result.success();
        } catch (Exception e) {
            LOGGER.error("删除商品失败：{}", e.getMessage());
            return Result.error("-1", "删除商品失败：" + e.getMessage());
        }
    }

   private Integer deleteRelate(Product product) {
        Long id = product.getId();
       int carouselResult = carouselItemMapper.delete(new LambdaQueryWrapper<CarouselItem>().eq(CarouselItem::getProductId, id));
       if (carouselResult < 0) {
           LOGGER.error("删除关联轮播图记录失败，商品ID：{}", id);
           return -1;
//           return Result.error("-1", "删除关联轮播图记录失败");
       }

       // 删除关联物流记录
       // 通过订单表获取所有与该商品ID关联的订单ID
       List<Order> orders = orderMapper.selectList(new LambdaQueryWrapper<Order>().eq(Order::getProductId, id));
       if (orders != null && !orders.isEmpty()) {
           List<Long> orderIds = orders.stream().map(Order::getId).collect(Collectors.toList());
           // 根据订单ID删除物流记录
           int logisticsResult = logisticsMapper.delete(new LambdaQueryWrapper<Logistics>().in(Logistics::getOrderId, orderIds));
           if (logisticsResult < 0) {
               LOGGER.error("删除关联物流记录失败，商品ID：{}", id);
               return -2;
//               return Result.error("-1", "删除关联物流记录失败");
           }
       }

       // 删除关联订单记录
       int orderResult = orderMapper.delete(new LambdaQueryWrapper<Order>().eq(Order::getProductId, id));
       if (orderResult < 0) {
           LOGGER.error("删除关联订单记录失败，商品ID：{}", id);
           return -3;
//           return Result.error("-1", "删除关联订单记录失败");
       }



       // 删除关联收藏记录
       int favoriteResult = favoriteMapper.delete(new LambdaQueryWrapper<Favorite>().eq(Favorite::getProductId, id));
       if (favoriteResult < 0) {
           LOGGER.error("删除关联收藏记录失败，商品ID：{}", id);
//           return Result.error("-1", "删除关联收藏记录失败");
           return -4;
       }

       int reviewResult = reviewMapper.delete(new LambdaQueryWrapper<Review>().eq(Review::getProductId, id));
       if (reviewResult < 0) {
           LOGGER.error("删除关联评价记录失败，商品id：{}", id);
           return -5;
       }

       int cartResult = cartMapper.delete(new LambdaQueryWrapper<Cart>().eq(Cart::getProductId, id));
       if (cartResult < 0) {
           LOGGER.error("删除关联购物车记录失败，商品ID：{}", id);
           return -6;
       }

       int stockInResult = stockInMapper.delete(new LambdaQueryWrapper<StockIn>().eq(StockIn::getProductId, id));
       if (stockInResult < 0) {
           LOGGER.error("删除关联入库记录失败，商品ID：{}", id);
           return -7;
       }
       int stockOutResult = stockOutMapper.delete(new LambdaQueryWrapper<StockOut>().eq(StockOut::getProductId, id));
       if (stockOutResult < 0) {
           LOGGER.error("删除关联出库记录失败，商品ID：{}", id);
           return -8;
       }
       return  1;


    }

    public Result<?> getProductById(Long productId) {
        Product product = productMapper.selectById(productId);
        if (product != null) {
            // 填充关联信息
            product.setMerchant(userMapper.selectById(product.getMerchantId()));
            product.setCategory(categoryMapper.selectById(product.getCategoryId()));
            return Result.success(product);
        }
        return Result.error("-1", "未找到商品");
    }


    public Page<Product> getProductsByPage(String name, Long categoryId, Long merchantId, Integer status,
                                           Integer currentPage, Integer size, String sortField, String sortOrder,
                                           Double minPrice, Double maxPrice) {
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();

        // 添加基本查询条件
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like(Product::getName, name);
        }
        if (categoryId != null) {
            queryWrapper.eq(Product::getCategoryId, categoryId);
        }
        if (merchantId != null) {
            queryWrapper.eq(Product::getMerchantId, merchantId);
        }
        if (status != null) {
            queryWrapper.eq(Product::getStatus, status);
        }

        // 处理排序
        boolean isAsc = "asc".equalsIgnoreCase(sortOrder);
        if (StringUtils.isNotBlank(sortField)) {
            switch (sortField) {
                case "sales":
                    queryWrapper.orderBy(true, isAsc, Product::getSalesCount);
                    break;
                case "price":
                    // 对于价格排序，使用自定义SQL考虑折扣价格
                    String orderDirection = isAsc ? "ASC" : "DESC";
                    queryWrapper.apply("1=1")  // 添加一个空条件，防止语法错误
                        .last("ORDER BY CASE WHEN is_discount = 1 THEN discount_price ELSE price END " + orderDirection);
                    break;
                default:
                    queryWrapper.orderByDesc(Product::getCreatedAt);
            }
        } else {
            queryWrapper.orderByDesc(Product::getCreatedAt);
        }

        // 添加价格区间筛选
        if (minPrice != null || maxPrice != null) {
            queryWrapper.and(wrapper -> {
                // 使用CASE WHEN语句根据是否有折扣选择正确的价格字段
                if (minPrice != null) {
                    wrapper.apply("(CASE WHEN is_discount = 1 THEN discount_price ELSE price END) >= {0}", minPrice);
                }
                if (maxPrice != null) {
                    wrapper.apply("(CASE WHEN is_discount = 1 THEN discount_price ELSE price END) <= {0}", maxPrice);
                }
            });
        }

        // 创建分页对象并执行查询
        Page<Product> page = new Page<>(currentPage, size);
        Page<Product> result = productMapper.selectPage(page, queryWrapper);

        // 填充关联信息
        result.getRecords().forEach(product -> {
            product.setMerchant(userMapper.selectById(product.getMerchantId()));
            product.setCategory(categoryMapper.selectById(product.getCategoryId()));
        });

        return result;
    }

    public Result<?> updateProductStatus(Long id, Integer status) {
        Product product = productMapper.selectById(id);
        if (product == null) {
            return Result.error("-1", "未找到商品");
        }
        product.setStatus(status);
        int result = productMapper.updateById(product);
        if (result > 0) {
            LOGGER.info("更新商品状态成功，商品ID：{}，新状态：{}", id, status);
            return Result.success();
        }
        return Result.error("-1", "更新商品状态失败");
    }

    public Result<?> deleteBatch(List<Long> ids) {
        try {
            // 检查每个商品是否存在关联记录
            for (Long id : ids) {
                Product product = productMapper.selectById(id);
                Integer res = deleteRelate(product);
                if (res < 0) {
                    return Result.error("-1", "删除关联记录失败，商品名称:"+product.getName());
                }
            }

            int result = productMapper.deleteBatchIds(ids);
            if (result > 0) {
                LOGGER.info("批量删除商品成功，删除数量：{}", result);
                return Result.success();
            }
            return Result.error("-1", "批量删除商品失败");
        } catch (Exception e) {
            LOGGER.error("批量删除商品失败：{}", e.getMessage());
            return Result.error("-1", "批量删除商品失败：" + e.getMessage());
        }
    }
    @Transactional

    public Result<?> updateBatchStatus(List<Long> ids, Integer status) {
        try {
            // 检查状态值是否有效
            if (status != 0 && status != 1) {
                return Result.error("-1", "无效的商品状态值");
            }

            // 检查商品是否存在
            List<Product> products = productMapper.selectBatchIds(ids);
            if (products.isEmpty()) {
                return Result.error("-1", "未找到指定商品");
            }
            if (products.size() != ids.size()) {
                return Result.error("-1", "部分商品不存在");
            }

            // 逐个更新商品状态
            int successCount = 0;
            for (Product product : products) {
                product.setStatus(status);
                int result = productMapper.updateById(product);
                if (result > 0) {
                    successCount++;
                }
            }

            if (successCount == products.size()) {
                LOGGER.info("批量更新商品状态成功，更新数量：{}，新状态：{}", successCount, status);
                return Result.success();
            }
            return Result.error("-1", "部分商品状态更新失败");
        } catch (Exception e) {
            LOGGER.error("批量更新商品状态失败：{}", e.getMessage());
            return Result.error("-1", "批量更新商品状态失败：" + e.getMessage());
        }
    }

    /**
     * 获取商品统计数据
     * @param merchantId 商户ID，可为空
     * @return 统计数据结果
     */
    public Result<?> getProductStatistics(Long merchantId) {
        try {
            Map<String, Object> statistics = new HashMap<>();
            
            // 构建基础查询条件
            LambdaQueryWrapper<Product> baseWrapper = new LambdaQueryWrapper<>();
            if (merchantId != null) {
                baseWrapper.eq(Product::getMerchantId, merchantId);
            }
            
            // 在售商品数量
            LambdaQueryWrapper<Product> onSaleWrapper = new LambdaQueryWrapper<>();
            if (merchantId != null) {
                onSaleWrapper.eq(Product::getMerchantId, merchantId);
            }
            onSaleWrapper.eq(Product::getStatus, 1);
            Long onSaleCount = productMapper.selectCount(onSaleWrapper);
            statistics.put("onSaleCount", onSaleCount);
            
            // 下架商品数量
            LambdaQueryWrapper<Product> offSaleWrapper = new LambdaQueryWrapper<>();
            if (merchantId != null) {
                offSaleWrapper.eq(Product::getMerchantId, merchantId);
            }
            offSaleWrapper.eq(Product::getStatus, 0);
            Long offSaleCount = productMapper.selectCount(offSaleWrapper);
            statistics.put("offSaleCount", offSaleCount);
            
            // 促销商品数量
            LambdaQueryWrapper<Product> discountWrapper = new LambdaQueryWrapper<>();
            if (merchantId != null) {
                discountWrapper.eq(Product::getMerchantId, merchantId);
            }
            discountWrapper.eq(Product::getIsDiscount, 1);
            Long discountCount = productMapper.selectCount(discountWrapper);
            statistics.put("discountCount", discountCount);
            
            // 销量最高的商品
            LambdaQueryWrapper<Product> topSalesWrapper = new LambdaQueryWrapper<>();
            if (merchantId != null) {
                topSalesWrapper.eq(Product::getMerchantId, merchantId);
            }
            topSalesWrapper.orderByDesc(Product::getSalesCount);
            topSalesWrapper.last("LIMIT 1");
            Product topSalesProduct = productMapper.selectOne(topSalesWrapper);
            if (topSalesProduct != null) {
                // 填充关联信息
                topSalesProduct.setCategory(categoryMapper.selectById(topSalesProduct.getCategoryId()));
                statistics.put("topSalesProduct", topSalesProduct);
            }
            
            // 商品总数
            Long totalCount = productMapper.selectCount(baseWrapper);
            statistics.put("totalCount", totalCount);
            
            return Result.success(statistics);
        } catch (Exception e) {
            LOGGER.error("获取商品统计数据失败：{}", e.getMessage());
            return Result.error("-1", "获取商品统计数据失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取销量排行商品列表
     * @param limit 返回数量限制
     * @return 销量排行商品列表
     */
    public Result<?> getTopSalesProducts(Integer limit) {
        try {
            // 构建查询条件：只查询上架商品，按销量降序排序
            LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Product::getStatus, 1)
                      .orderByDesc(Product::getSalesCount)
                      .last("LIMIT " + limit);
            
            List<Product> products = productMapper.selectList(queryWrapper);
            
            // 填充关联信息
            products.forEach(product -> {
                product.setCategory(categoryMapper.selectById(product.getCategoryId()));
            });
            
            // 构造分页对象以保持与其他接口返回格式一致
            Page<Product> page = new Page<>();
            page.setRecords(products);
            page.setTotal(products.size());
            
            return Result.success(page);
        } catch (Exception e) {
            LOGGER.error("获取销量排行商品失败：{}", e.getMessage());
            return Result.error("-1", "获取销量排行商品失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取最新上架商品
     * @param limit 返回数量限制
     * @return 最新上架商品列表
     */
    public Result<?> getNewProducts(Integer limit) {
        try {
            // 构建查询条件：只查询上架商品，按更新时间降序排序
            LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Product::getStatus, 1)
                      .orderByDesc(Product::getUpdatedAt)
                      .last("LIMIT " + limit);
            
            List<Product> products = productMapper.selectList(queryWrapper);
            
            // 填充关联信息
            products.forEach(product -> {
                product.setCategory(categoryMapper.selectById(product.getCategoryId()));
            });
            
            // 构造分页对象以保持与其他接口返回格式一致
            Page<Product> page = new Page<>();
            page.setRecords(products);
            page.setTotal(products.size());
            
            return Result.success(page);
        } catch (Exception e) {
            LOGGER.error("获取最新上架商品失败：{}", e.getMessage());
            return Result.error("-1", "获取最新上架商品失败：" + e.getMessage());
        }
    }
} 